﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows;

/*
* 源码已托管：https://gitee.com/dlgcy/WPFTemplateLib
*/
namespace WPFTemplateLib.Enhance
{
	/// <summary>
	/// 固定容量的 <see cref="ObservableCollection&lt;T&gt;"/>
	/// </summary>
	public class FixedCountObservableCollection<T> : ObservableCollection<T>
	{
		private int _count;
		private bool _removeOldest;

		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="count">最多的元素数</param>
		/// <param name="removeOldest">true-移除最旧的 [默认], false-移除最新的</param>
		public FixedCountObservableCollection(int count = 100, bool removeOldest = true)
		{
			_count = count;
			_removeOldest = removeOldest;
		}

		/// <inheritdoc />
		protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
		{
			base.OnCollectionChanged(e);
			if (e.Action == NotifyCollectionChangedAction.Add)
			{
				Application.Current.Dispatcher.BeginInvoke(new Action(() =>
				{
					int more = Count - _count;
					if (more <= 0)
					{
						return;
					}

					for (int i = 0; i < more; i++)
					{
						if (_removeOldest)
						{
							RemoveAt(0);
						}
						else
						{
							RemoveAt(Count - 1);
						}
					}
				}));
			}
		}
	}
}
